package com.honeywell.iotserver.rabbitmq;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.honeywell.iotserver.entity.OnOffLogEntity;
import com.honeywell.iotserver.repository.DeviceAlarmScheduleRepository;
import com.honeywell.iotserver.repository.OnOffLogRepository;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@EnableScheduling
@Component
public class DeviceAlarmSchedule {
	
	private static Logger logger = LoggerFactory.getLogger(DeviceAlarmSchedule.class);
	@Autowired
	private DeviceAlarmScheduleRepository deviceAlarmScheduleRepository;
	
	@Autowired
	private OnOffLogRepository onOffLogRepository;
	
	@Autowired
	MessageSender messageSender;
	
	@Scheduled(cron = "0/30 * * * * ?")//每30秒执行一次，将来需要从配置文件里面读出来
	public void fetchAlarm() {
		List<Object> list = deviceAlarmScheduleRepository.seletemaxdate(); //1分钟，将来需要从配置文件里面读出来
		if (list != null && list.size() > 0) {
			List<String> uuidlist = new ArrayList<String>();
			List<OnOffLogEntity> onOffLogList = new ArrayList<OnOffLogEntity>();
			Map<String, String> messageMap = new HashMap<String,String>();
			for (Object object : list) {
				Object[] objects = (Object[]) object;
				Date date = (Date)objects[0];
				String uuid =(String) objects[1];
				Date heartp_time =(Date) objects[2];
				if((date.getTime() - heartp_time.getTime())/(1000*60)>=1) {
					uuidlist.add(uuid);
					onOffLogList.add(new OnOffLogEntity(uuid,0,new Date()));
					messageMap.put(uuid, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(heartp_time));
					logger.info("DeviceAlarmSchedule-[NowTime:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)+",uuid:"+uuid+",heartp_time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(heartp_time)+"]");
				}
				
			}

			if(uuidlist.size() >0)deviceAlarmScheduleRepository.updatestatus(uuidlist);
			if(onOffLogList.size() >0) onOffLogRepository.saveAll(onOffLogList);
			if(messageMap.size() >0) {
				Iterator<Map.Entry<String, String>> entries = messageMap.entrySet().iterator(); 
				while (entries.hasNext()) { 
				  Map.Entry<String, String> entry = entries.next(); 
				  String message = "{\"uuid\":\""+entry.getKey()+"\",\"status\":"+0+",\"time\":\""+entry.getValue()+"\"}";
				  messageSender.sendOnOffAlarmMessage(message);
				}
			}
		}	
	}
}
